package cn.com.klun.tjy;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

@Controller
public class StartSpiderTask implements ApplicationListener {
    private Logger logger = LoggerFactory.getLogger(StartSpiderTask.class);
    private SchedulerFactory sf = new StdSchedulerFactory();
    private Scheduler sched;
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        logger.info("启动定时爬取数据更新日K...");
        try {
            sched = sf.getScheduler();
            JobDetail job = newJob(SpiderJob.class).withIdentity("spiderHtml", "spiderGroup").build();
            CronTrigger trigger = newTrigger().withIdentity("spiderTrigger", "spiderGroup").withSchedule(cronSchedule("0 30 22 * * ?")).build();
            Date ft = sched.scheduleJob(job, trigger);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            logger.info(job.getKey() + " 已被安排执行于: " + sdf.format(ft) + "，并且以如下重复规则重复执行: " + trigger.getCronExpression());
            sched.start();
        } catch (Exception e) {
            logger.info("定时任务写入异常{}",e);
        }
    }
}
